﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace CommonUtils
{
    [Serializable]
    public class ServerMessage<TType>
    {
        private static volatile int m_NextMsgId = 0;
        
        private TType m_MessageType;
        private object m_Params;
        private int m_MsgID;

        public ServerMessage(TType type, object param)
        {
            m_MessageType = type;
            m_Params = param;
            m_MsgID = m_NextMsgId++;
        }

        public TType MessageType
        {
            get { return m_MessageType; }
            set { m_MessageType = value; }
        }

        public object Params
        {
            get { return m_Params; }
            set { m_Params = value; }
        }

        public int MsgID
        {
            get { return m_MsgID; }
            set { m_MsgID = value; }
        }

        public byte[] Serialize()
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                BinaryFormatter bf1 = new BinaryFormatter();
                bf1.Serialize(ms, this);
                return ms.ToArray();
            }
            catch
            {
                return null;
            }
        }

        public static ServerMessage<TType> Deserialize(byte[] bytes)
        {
            try
            {
                MemoryStream ms = new MemoryStream(bytes);
                BinaryFormatter bf1 = new BinaryFormatter();
                ms.Position = 0;
                return (ServerMessage<TType>)bf1.Deserialize(ms);
            }
            catch
            {

                return null;
            }
        }
    }
}
